/**
 * Copyright (C), 2020-2020, 软件公司
 * FileName: RPCServer
 * Author:   cakin
 * Date:     2020/5/12
 * Description:
 */
package com.rabbitmq.rpc;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.util.ConnectionUtils;
import lombok.extern.slf4j.Slf4j;

import static com.rabbitmq.common.Constant.NUM2;

/**
 * @ClassName: RPCServer
 * @Description: RPC服务端
 * @Date: 2020/5/12
 * @Author: cakin
 */
@SuppressWarnings("ALL")
@Slf4j
public class RPCServer {
    /**
     * 请求队列
     */
    private static final String RPC_QUEUE_NAME = "rpc_queue";

    public static void main( String[] args ) throws Exception {
        // 创建连接和信道
        Connection connection = ConnectionUtils.getConnection();
        Channel channel = connection.createChannel();
        // 声明一个请求队列
        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);
        // 创建一个消费者
        QueueingConsumer consumer = new QueueingConsumer(channel);
        // 消费者采用推模式，监听RPC_QUEUE_NAME队列中消息
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        log.info(" [x] Awaiting RPC requests");

        while (true) {
            log.info(" before");
            // 如果没收到消息，会阻塞
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            log.info(" after");
            // 解析消息中传过来的属性
            BasicProperties props = delivery.getProperties();
            // 响应消息要携带correlationId
            BasicProperties replyProps = new BasicProperties.Builder().correlationId(props.getCorrelationId()).build();
            // 解析消息内容
            String message = new String(delivery.getBody());
            int n = Integer.parseInt(message);
            log.info(" [.] fib(" + message + ")");
            // 计算后的响应消息
            String repsonse = "" + fib(n);
            // 响应队列是props.getReplyTo() ，响应属性replyProps 携带 correlationId
            channel.basicPublish("", props.getReplyTo(), replyProps, repsonse.getBytes());
            // 手动发送确认消息
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }
    }

    /**
     * 功能描述：斐波那契递归算法
     *
     * @author cakin
     * @date 2020/5/12
     * @param n 计算基数
     * @return int 计算值
     * @throws Exception 抛异常
     */
    private static int fib( int n ) throws Exception {
        if (n == 0) {
            return 0;
        }
        if (n == 1) {
            return 1;
        }
        return fib(n - 1) + fib(n - NUM2);
    }
}

